﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace AspDotNet.Framework.Mvc.FirstDemo.Controllers
{
    public class ActionResultController : BaseController
    {
        public ActionResult ActionResult()
        {
            return View();
        }

        public ContentResult ContentResult1()
        {
            return Content("body{font-family: SimHei; font-size:1.2em}");
        }

        public ContentResult ContentResult2()
        {
            return Content("body{font-family: SimHei; font-size:1.2em}", "text/css");
        }

        public ContentResult ContentResult3()
        {
            return Content("body{font-family: SimHei; font-size:1.2em}", "text/css", Encoding.UTF8);
        }

        public EmptyResult EmptyResult()
        {
            //return new EmptyResult();
            //同
            return null;
        }

        public FilePathResult FilePathResult()
        {
            string file = GetRandomFile();
            return File(file, $"image/{Path.GetExtension(file).TrimStart('.')}");
        }

        public FileContentResult FileContentResult()
        {
            string file = GetRandomFile();
            return File(System.IO.File.ReadAllBytes(file), $"image/{Path.GetExtension(file).TrimStart('.')}");
        }

        public FileStreamResult FileStreamResult()
        {
            string file = GetRandomFile();
            return File(System.IO.File.Open(file, FileMode.Open), $"image/{Path.GetExtension(file).TrimStart('.')}");
        }

        public JsonResult JsonResult()
        {
            return Json(new { Name = "Jine", Age = "20", AccessTime = DateTime.Now.ToString() }, JsonRequestBehavior.AllowGet);
        }

        public RedirectResult RedirectResult()
        {
            return Redirect($"/?重定向到主页");
        }

        public RedirectToRouteResult RedirectToRouteResult()
        {
            return RedirectToAction("index","home");
        }

        public JavaScriptResult JavaScriptResult()
        {
            return JavaScript("<script>alert('Hello !!!');</script>");
        }

        public PartialViewResult PartialViewResult()
        {
            return PartialView();
        }

        public HttpUnauthorizedResult HttpUnauthorizedResult()
        {
            //return HttpUnauthorizedResult();
            return null;
        }

        public ViewResult ViewResult()
        {
            return View();
        }

        private string GetRandomFile()
        {
            var rNum = new Random().Next(1, 4).ToString();

            var files = Directory.GetFiles(Server.MapPath($"~/images"));
            string file = files.FirstOrDefault(p => Path.GetFileNameWithoutExtension(p).Equals(rNum)) ?? files[0];
            return file;
        }
    }
}